package com.yyf.springboot2.controller;


import com.alibaba.fastjson.JSONObject;
import com.yyf.springboot2.common.*;
import com.yyf.springboot2.entity.TUser;
import com.yyf.springboot2.entity.WXSessionModel;
import com.yyf.springboot2.service.TUserService;
import org.apache.http.HttpRequest;
import org.springframework.util.DigestUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@RestController
public class LoginController {

    @Resource
    private RedisOperator redisOperator;
    @Resource
    private  TUserService userService;

//    @Resource
//    private Redis redis;

    @GetMapping("/test")
    public String test(){
        return  "hello";
    }

    @PostMapping("/wxlogin")
    @ResponseBody
    public ResultBean wxlogin(String code, HttpRequest request){
        //获取和微信绑定的用户账号信息

        String url = "https://api.weixin.qq.com/sns/jscode2session";
        Map<String,String> map = new HashMap<String,String>();
        map.put("appid","wx82f9c1fe520e526d");
        map.put("secret","4c94540604d0e2838443e51d3371edb1"); // 密码
        map.put("js_code",code);
        map.put("grant_type","authorization_code");

        String wxResult =  HttpClientUtil.doGet(url,map);
        System.out.println(wxResult);//获得{"session_key":"7Lup9ZAk1mmp\/pB2BiYbPA==","openid":"oHSdK5PTY7_A40JmN7TpaAxToKIM"}
        WXSessionModel wxSessionModel = JsonUtils.jsonToPojo(wxResult,WXSessionModel.class);
        //将用户信息存入数据库
        //进行登录成功的系统操作后,给微信小程序返回一个标识,表明该用户登录成功
        map.clear();
        Map<String,Object> ma = new HashMap<String,Object>();
        ma.put("token",wxSessionModel.getSession_key());
        ma.put("openId",wxSessionModel.getOpenid());
        //找到openid 绑定的用户，把用户id传给前台
        ma.put("uid","1");
        //生成盐值
        String salt = GenerateUtil.getRandomSalt();
        TUser loginUser = userService.getUserInfoById(1);
        //修改用户密码和盐值



//        redis.get("abc");
//        System.out.println(redis.get("abc")+"redis.get(\"abc\")");
        if(loginUser.getSalt() == null){
           // 给密码加盐
            String  password = GenerateUtil.md5AndSha("test",salt);
            userService.updatePassAndSalt(password,salt,loginUser.getId() );
        }


//        getCurrentDateString();
        System.out.println(DateAndTimeUtils.getCurrentDateString());
        String content = loginUser.getId()+"|"+IpUtil.getIpAddress()+"|"+DateAndTimeUtils.getCurrentDateString();
        String token = "";
        try {
            token =   AuthToken.encrypt(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        ma.put("token",token);

        JSONObject json = new JSONObject(ma);

        if(wxResult != ""){
            return  ResultBean.build(200,"登录成功",json);
        }
        return ResultBean.build(100,"微信登录失败",null);


    }


    @PostMapping("/login")
    private  ResultBean login(@RequestParam(name = "userName") String userName,
                              @RequestParam(name = "password") String password
                              ) {
        if (userName == null || userName.equals("")) {
            return ResultBean.build(500, "用户名不能为空", null);
        }
        if (password == null || password.equals("")) {
            return ResultBean.build(500, "密码不能为空", null);
        }

        TUser loginUser = userService.getUserByUsername(userName);
        // 根据电话号码找用户
        if (loginUser == null) {
            return ResultBean.build(500, "用户不存在", null);
        } else if (!loginUser.getPassword().equals(
                DigestUtils.md5DigestAsHex(password.getBytes()))) {
            return ResultBean.build(500, "密码错误", null);

        } else {
            if (loginUser.getIsDj().intValue() == 0) {
                return ResultBean.build(500, "该账户已被冻结", null);
            } else {
                String ip = WebUtil.getIpAddr();
                userService.updateLastTimeAndLoginCountAndLastIPById(
                        loginUser.getId(), ip);
                loginUser.setIp(ip);
                WebUtil.setSession(Constants.LOGIN_USER, loginUser);
                JSONObject  jsonObject = new JSONObject();
                jsonObject.put("id",loginUser.getId());
                jsonObject.put("username",loginUser.getUsername());
                //专门可以返回给前端的数据
                TUser user = userService.getUserInfoById(loginUser.getId());
                return ResultBean.build(200,"登录成功",jsonObject);
        }

        }
    }

}
